<!--素材库-->
<template>
  <div class="material-library">
    <el-dialog title="素材库" v-model="dialogVisible" width="1200px" :before-close="handleClose">
      <el-card shadow="hover">
        <el-form ref="queryFormRef" :model="queryParams" :inline="true">
          <el-form-item label="文件名" prop="filename">
            <el-input v-model="queryParams.filename" placeholder="请输入文件名" clearable @keyup.enter="handleQuery" />
          </el-form-item>
          <el-form-item label="素材ID" prop="materialId">
            <el-input v-model="queryParams.materialId" placeholder="请输入素材ID" clearable @keyup.enter="handleQuery" />
          </el-form-item>
          <el-form-item label="时间" prop="advertiserId">
            <el-date-picker
              v-model="time"
              type="daterange"
              range-separator="至"
              start-placeholder="开始时间"
              end-placeholder="结束时间"
              format="YYYY-MM-DD"
              value-format="YYYY-MM-DD"
              @change="handleTimeChange"
            />
          </el-form-item>
          <el-form-item>
            <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
            <el-button icon="Refresh" @click="resetQuery">重置</el-button>
            <el-button type="primary" @click="handleSync">同步</el-button>
            <el-button>已选数量 {{ selectedRowsLists.length }}</el-button>
            <span></span>
          </el-form-item>
        </el-form>
      </el-card>
      <div class="material-content" v-loading="loading">
        <el-table
          ref="tableRef"
          :data="materialLibraryList"
          style="width: 100%"
          height="100%"
          center
          border
          @row-click="handleRowClick"
          @select="handleRowClick2"
          @select-all="handleSelectAll"
          row-key="id"
        >
          <el-table-column type="selection" width="55" :reserve-selection="true" />
          <el-table-column prop="date" label="素材" width="180" sortable>
            <template #default="scope">
              <img
                @click="handleImgView(scope.row)"
                style="cursor: pointer"
                :src="fileTypes == 'image' ? scope.row.url : scope.row.posterUrl"
                alt=""
              />
            </template>
          </el-table-column>
          <el-table-column prop="filename" label="文件名" />
          <el-table-column prop="cost" label="消耗" />
          <el-table-column prop="materialId" label="素材id" />
          <el-table-column prop="format" label="图片格式" width="180" />
          <el-table-column prop="aigc" label="是否aigc生成">
            <template #default="scope">
              <span v-if="scope.row.aigc">是</span>
              <span v-else>否</span>
            </template>
          </el-table-column>
        </el-table>
      </div>
      <el-dialog title="预览" v-model="dialogImgVisible" append-to-body :close-on-click-modal="true">
        <img :src="selectedRow.url" style="max-width: 100%; max-height: 70vh; display: block; margin: 0 auto" alt="" v-if="fileTypes == 'image'" />
        <video :src="selectedRow.url" controls="controls" style="max-width: 100%; max-height: 70vh; display: block; margin: 0 auto"></video>
        <template #footer>
          <div class="material-footer">
            <el-button type="primary" @click="dialogImgVisible = false">关闭</el-button>
          </div>
        </template>
      </el-dialog>
      <template #footer>
        <div class="material-footer">
          <el-button type="primary" @click="handleSubmit">确定</el-button>
          <el-button @click="handleClose">取消</el-button>
        </div>
      </template>
      <pagination
        v-if="total > 0"
        v-model:total="total"
        v-model:page="queryParams.pageNum"
        v-model:limit="queryParams.pageSize"
        @pagination="props.fileType === 'video' ? handlegetVideoList() : handlegetImageList()"
        :ispage="true"
      />
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { getImageList, getVideoList, syncMaterial } from '@/api/advertisement/materialLibrary';
const props = defineProps([
  'isMaterialLibrary',
  'fileType',
  'selectedVioIndex',
  'videoTotals',
  'userList',
  'width',
  'height',
  'imageIds',
  'groupQos',
  'selected',
  'selectAdvertiserId',
  'myMaterialType',
  'mySelectAccountGroupQos',
  'selectedAccountIndex'
]);
import dayjs from 'dayjs';
const emit = defineEmits(['update:isMaterialLibrary', 'selectedRows', 'updateGroup', 'updateSelectAdvertiserId', 'selectAccountGroupQos']);
const { proxy } = getCurrentInstance() as ComponentInternalInstance;
import { useAppStore } from '@/store/modules/app';

import { he } from 'element-plus/es/locale/index.mjs';
import store from '@/store/index';
const appStore = useAppStore();
const tableRef = ref();
const dialogVisible = ref(false);
const dialogImgVisible = ref(false);
const selectedRow = ref();
const accountId = ref(appStore.accountId);
const materialLibraryList = ref([]);
const selectedRowsLists = ref([]);
const queryFormRef = ref();
const fileTypes = ref();
const total = ref(0);
const loading = ref(false);
const time = ref([dayjs().subtract(7, 'day').format('YYYY-MM-DD') + ' 00:00:00', dayjs().format('YYYY-MM-DD') + ' 23:59:59']);

const data = reactive<PageData<ProductStoreForm, EventAssetsQuery>>({
  queryParams: {
    pageNum: 1,
    pageSize: 100,
    filename: undefined,
    materialId: undefined,
    accountId: appStore.accountId,
    // advertiserId: 1820572205006868, // 测试
    advertiserId: undefined,
    assetId: undefined,
    assetName: undefined,
    with: props.width,
    height: props.height,
    startTime: '',
    endTime: '',
    params: {}
  }
});
const { queryParams } = toRefs(data);

// watch(
//   () => props.userList,
//   () => {
//     nextTick(() => {
//       queryParams.value.advertiserId = props.userList ? props.userList[0]?.id : '';
//       if (queryParams.value.advertiserId) {
//         props.fileType === 'video' ? handlegetVideoList() : handlegetImageList();
//       }
//     });
//   },
//   { immediate: true, deep: true }
// );

onMounted(() => {});
watch(
  () => props,
  (newVal, oldVal) => {
    dialogVisible.value = newVal.isMaterialLibrary;

    fileTypes.value = props.fileType;
    tableRef.value?.clearSelection();
    // if (props.fileType === 'video') {
    //   handlegetVideoList();
    // } else {
    //   handlegetImageList();
    // }
    nextTick(() => {
      queryParams.value.advertiserId = props.userList ? (props.myMaterialType == 1 ? props.userList[0]?.id : props.selectAdvertiserId) : '';
      if (props.myMaterialType == 3) {
        selectedRowsLists.value = [];
      }
      if (queryParams.value.advertiserId) {
        props.fileType === 'video' ? handlegetVideoList() : handlegetImageList();
      }
    });
  },
  { immediate: true, deep: true }
);
// 判断id 是否变化，就修改
watch(
  () => props.selectedVioIndex,
  (newVal, oldVal) => {
    tableRef.value?.clearSelection();
  }
);
/** 搜索按钮操作 */
const handleQuery = () => {
  queryParams.value.pageNum = 1;

  props.fileType === 'video' ? handlegetVideoList() : handlegetImageList();
};
/** 重置按钮操作 */
const resetQuery = () => {
  queryFormRef.value?.resetFields();
  handleQuery();
};
// const handleClearSelection = () => {
//   tableRef.value.clearSelection();
// };
/**
 * 支持所有原生video事件
 */
const onPlay = (ev) => {
  console.log('播放');
};
const onPause = (ev) => {
  console.log(ev, '暂停');
};
const onTimeupdate = (ev) => {
  console.log(ev, '时间更新');
};
const onCanplay = (ev) => {
  console.log(ev, '可以播放');
};
//
const handleSync = async () => {
  proxy?.$modal.loading('');
  let params = {
    accountId: appStore.accountId,
    advertiserId: props.selectAdvertiserId ? props.selectAdvertiserId : props.userList[0]?.id,
    startTime: time.value[0],
    endTime: time.value[1]
  };
  await syncMaterial(params);
  // syncMaterial(params).then((res) => {
  //   ElMessage({
  //     message: '同步成功',
  //     type: 'success'
  //   });
  props.fileType === 'video' ? handlegetVideoList() : handlegetImageList();
  // });
  proxy?.$modal.closeLoading();
};
const handleSubmit = () => {
  if (!tableRef.value.getSelectionRows().length) {
    ElMessage({
      message: '请选择素材',
      type: 'error'
    });
    return;
  }
  const selectedRows = tableRef.value.getSelectionRows();

  // if (props.videoTotals < selectedRows.length) {
  //   ElMessage({
  //     message: '视频数量不能超过数量规定的最大值，请先设置总数',
  //     type: 'error'
  //   });
  //   return;
  // }
  emit('updateSelectAdvertiserId', props.selectAdvertiserId);

  if (!props.imageIds) {
    // 分账户
    if (props.myMaterialType == '3') {
      if (props.selectedAccountIndex === -1) {
        const arrLen = Math.ceil(selectedRows.length / props.videoTotals);
        // 平均分配 视频
        let data = Array.from({ length: arrLen }, () => []);
        selectedRows.forEach((row, index) => {
          const groupIndex = Math.floor(index / props.videoTotals); // 计算当前行应该分配到哪个组
          data[groupIndex].push(row); // 将行分配到对应组
        });
        emit('selectedRows', data);
      } else {
        const temp = JSON.parse(JSON.stringify(props.mySelectAccountGroupQos));
        const len = temp[props.selectedAccountIndex]?.videoMaterialList.length;
        if (len + selectedRows.length > props.videoTotals) {
          ElMessage({
            message: '超过数量限制',
            type: 'error'
          });
          return;
        }
        if (len > 0) {
          // 使用 concat 方法合并数组
          temp[props.selectedAccountIndex].videoMaterialList = temp[props.selectedAccountIndex].videoMaterialList.concat(
            JSON.parse(JSON.stringify(selectedRows))
          );
        } else {
          temp[props.selectedAccountIndex].videoMaterialList = selectedRows;
        }
        // emit('selectAccountGroupQos', temp);
        emit('updateGroup', temp);
      }
    } else {
      // 复用
      if (props.selectedVioIndex === -1) {
        const arrLen = Math.ceil(selectedRows.length / props.videoTotals);
        // 平均分配 视频
        let data = Array.from({ length: arrLen }, () => []);
        selectedRows.forEach((row, index) => {
          const groupIndex = Math.floor(index / props.videoTotals); // 计算当前行应该分配到哪个组
          data[groupIndex].push(row); // 将行分配到对应组
        });
        emit('selectedRows', data);
      } else {
        const temp = JSON.parse(JSON.stringify(props.groupQos));
        const len = temp[props.selectedVioIndex]?.videoMaterialList.length;
        if (len + selectedRows.length > props.videoTotals) {
          ElMessage({
            message: '超过数量限制',
            type: 'error'
          });
          return;
        }
        if (len > 0) {
          // 使用 concat 方法合并数组
          temp[props.selectedVioIndex].videoMaterialList = temp[props.selectedVioIndex].videoMaterialList.concat(selectedRows);
        } else {
          temp[props.selectedVioIndex].videoMaterialList = selectedRows;
        }
        emit('updateGroup', temp);
      }
    }
  } else {
    const selectedRows = tableRef.value.getSelectionRows();
    emit('selectedRows', selectedRows);
  }

  emit('update:isMaterialLibrary', false);
  dialogVisible.value = false;
};
const handleRowClick = (row) => {
  // 切换当前行的选中状态
  tableRef.value.toggleRowSelection(row);
  selectedRowsLists.value = tableRef.value.getSelectionRows();
};
const handleRowClick2 = (row, rows) => {
  const index = selectedRowsLists.value.findIndex((subitem) => subitem.materialId === rows.materialId);
  if (index === -1) {
    selectedRowsLists.value.push(rows);
  } else {
    selectedRowsLists.value.splice(index, 1);
  }
};
const handleSelectAll = (selection) => {
  selectedRowsLists.value = tableRef.value.getSelectionRows();
};
const handleImgView = (row) => {
  dialogImgVisible.value = true;
  selectedRow.value = row;
};
const handleViewView = (row) => {
  dialogImgVisible.value = true;
  selectedRow.value = row;
};

// 获取图片列表
const handlegetImageList = async () => {
  loading.value = true;
  const res = await getImageList(queryParams.value);
  materialLibraryList.value = res.rows;
  if (props.selected.length) {
    materialLibraryList.value.map((item) => {
      props.selected.map((subitem) => {
        if (subitem.id === item.id) {
          setTimeout(() => {
            tableRef.value?.toggleRowSelection(item, true);
          }, 0);
        }
      });
    });
  }
  total.value = res.total;
  loading.value = false;
};
// 获取视频列表
const handlegetVideoList = async () => {
  loading.value = true;
  if (time.value.length > 0 && (time.value[0].length > 12 || time.value[1].length > 12)) {
    queryParams.value.startTime = time?.value[0];
    queryParams.value.endTime = time?.value[1];
  } else {
    queryParams.value.startTime = time?.value[0] + ' 00:00:00';
    queryParams.value.endTime = time?.value[1] + ' 23:59:59';
  }
  const res = await getVideoList(queryParams.value);
  materialLibraryList.value = res.rows;

  if (props.groupQos?.length) {
    materialLibraryList.value.map((item) => {
      props.groupQos.map((subitem) => {
        subitem.videoMaterialList.map((child) => {
          if (child.videoId === item.id) {
            setTimeout(() => {
              tableRef.value?.toggleRowSelection(item, true);
            }, 0);
          }
        });
      });
    });
  }

  total.value = res.total;
  loading.value = false;
};
// 分页
const handleCurrentChange = (val: number) => {
  queryParams.value.pageNum = val;
  props.fileType === 'video' ? handlegetVideoList() : handlegetImageList();
};
const handleClose = () => {
  emit('update:isMaterialLibrary', false);
  dialogVisible.value = false;
};
</script>

<style scoped lang="scss">
.material-content {
  height: 500px;
  overflow-y: scroll;
  img {
    width: 120px;
    height: 180px;
  }
}
</style>
